import React, {Component} from 'react';
import {InputItem, Modal, PickerView} from 'antd-mobile';
import {array, func, number, string} from 'prop-types';

class AddressSelector extends Component {
    static propTypes = {
        options: array.isRequired,
        value: string.isRequired,
        cols: number.isRequired,
        onChange: func.isRequired,
        delimiter: string.isRequired,
    };
    state = {
        modalVisible: false,
        selected: [],
    };

    showModal = () => {
        this.setState({
            modalVisible: true,
        });
    };
    hideModal = () => {
        this.setState({
            modalVisible: false,
        })
    };
    onSelectChange = arr => {
        this.setState({
            selected: arr,
        })
    };
    onSelected = () => {
        this.hideModal();
        this.props.onChange(this.state.selected);
    };

    render() {
        const {modalVisible, selected} = this.state;
        const {options, cols, value} = this.props;
        return (
            <>
                <InputItem onClick={this.showModal} value={value}>地址选择</InputItem>
                <Modal visible={modalVisible} transparent title="地址选择"
                       footer={[{text: '取消', onPress: this.hideModal}, {text: '确定', onPress: this.onSelected}]}>
                    <PickerView data={options} cols={cols} value={selected} onChange={this.onSelectChange}/>
                </Modal>
            </>
        );
    }
}

export default AddressSelector;

export const ADDRESS_DELIMITER = '|';
export const asOptions = (cities, ctx, cols) => {
    let deep = cols;
    let hasEndNodes = false;
    for (const name in cities) {
        if (!cities.hasOwnProperty(name)) {
            continue;
        }
        const item = {
            label: name,
            value: name,
            key: name,
            children: [],
        };
        const values = cities[name];

        if (values) {
            if (typeof (values) === 'string') {
                item.children.push({
                    label: values,
                    value: values,
                    key: values,
                });
                hasEndNodes = true;
            } else {
                const ndeep = asOptions(values, item.children, cols + 1);
                if (ndeep > deep) {
                    deep = ndeep;
                }
            }
        }
        ctx.push(item);
    }
    return hasEndNodes ? deep + 1 : deep;
};
